import BDKeyboardKit
import BDKit
import BDiOS
import ProgressHUD
import UIKit

struct TaskModel: Decodable {
  let taskId: Int?
}

class MainTabBarController: UITabBarController {

  let rimeViewModel: BDRimeViewModel
  let rimeContext: BDRimeContext
  init() {
    rimeContext = BDRimeContext()
    rimeViewModel = BDRimeViewModel(rimeContext: rimeContext)
    super.init(nibName: nil, bundle: nil)
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    setupTabBarAppearance()
    getTask()
    WXApiManager.shared.delegate = WXApiHandler.shared
  }

  private func addSubControllers(taskId: Int) {
    let tabs: [(UIViewController, String, String, String)] = [
      (
        KeyboardViewController(taskId: taskId),
        "键盘",
        "tab_keyboard_normal",
        "tab_keyboard_selected"
      ),
      (
        CustomerViewController(taskId: taskId),
        "客户",
        "tab_customer_normal",
        "tab_customer_selected"
      ),
      (
        ProductListViewController(taskId: taskId),
        "商品",
        "tab_product_normal",
        "tab_product_selected"
      ),
      (
        ProfileViewController(taskId: taskId),
        "我的",
        "tab_profile_normal",
        "tab_profile_selected"
      ),
    ]

    let controllers = tabs.map { controller, title, imageName, selectedImageName in
      let nav = UINavigationController(rootViewController: controller)
      nav.tabBarItem = UITabBarItem(
        title: title,
        image: UIImage(named: imageName),
        selectedImage: UIImage(named: selectedImageName)
      )
      return nav
    }

    viewControllers = controllers
  }

  private func setupTabBarAppearance() {
    let appearance = UITabBarAppearance()
    appearance.configureWithOpaqueBackground()
    tabBar.standardAppearance = appearance
    if #available(iOS 15.0, *) {
      tabBar.scrollEdgeAppearance = appearance
    }

    tabBar.tintColor = UIColor(
      red: 255 / 255,
      green: 99 / 255,
      blue: 31 / 255,
      alpha: 1
    )
  }

  private func getTask() {
    //        ProgressHUD.animate("加载中...", interaction: false)
    HttpClient.shared.postWithAutoHUD(endpoint: "/latestTask", body: [:], showHUD: false) {
      [weak self] (result: Result<TaskModel, String>) in
      guard let self = self else { return }
      switch result {
      case .success(let task):
        guard let taskId = task.taskId else {
          ProgressHUD.failed("获取TaskId失败，请重新登录")
          self.gotoLoginPage()
          return
        }
        // 保存 taskId
        UserDefaults.baodan.set(taskId, forKey: UserDefaults.taskIdKey)
        self.addSubControllers(taskId: taskId)
        //                ProgressHUD.succeed()
        // 加载键盘配置
        Task {
          do {
            try await self.setupKeyboard()
          } catch {
            ProgressHUD
              .failed("导入数据异常", interaction: false, delay: 2)
          }
        }
      case .failure(let errorMessage):
        ProgressHUD.failed("获取TaskID失败：\(errorMessage), 请重新登录")
        self.gotoLoginPage()
      }
    }
  }

  private func gotoLoginPage() {
    UserDefaults.baodan.removeObject(forKey: UserDefaults.taskIdKey)
    if let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate {
      let window = sceneDelegate.window
      UserDefaults.baodan.removeUserDataFromUserdefaults()

      // 切换根视图控制器
      UIView.transition(
        with: window!, duration: 0.5, options: .transitionCrossDissolve,
        animations: {
          window?.rootViewController = WelcomeViewController()  // 登录成功后，切换到主页面
        })
    }
  }

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

  }
}

extension MainTabBarController {

  func setupKeyboard() async throws {
    // 判断应用是否首次运行
    guard UserDefaults.standard.isFirstRunning else { return }

    // 判断是否首次运行
    ProgressHUD.animate("初次启动，需要编译键盘输入方案，请耐心等待……", interaction: false)
    try? await Task.sleep(nanoseconds: 300_000_000)  // 0.3 秒
    // 首次启动始化输入方案目录
    do {
        try FileManager.initializeSandboxUserDataDirectory(override: true, unzip: true)
        try FileManager.initializeSandboxBackupDirectory(override: true)
    } catch {
      print("rime init file directory error: \(error.localizedDescription)")
      throw error
    }

    var configuration = BaoDanAppDependencyContainer.shared.configuration

    // 部署 RIME
    try rimeViewModel.rimeContext.deployment(configuration: &configuration)

    // TODO: 内置雾凇方案，将默认选择方案改为雾凇拼音
    let rimeSchema = RimeSchema(schemaId: "rime_ice", schemaName: "雾凇拼音")
    rimeViewModel.rimeContext.selectSchemas = [rimeSchema]
    rimeViewModel.rimeContext.currentSchema = rimeSchema

    // 修改应用首次运行标志
    UserDefaults.standard.isFirstRunning = false

    BaoDanAppDependencyContainer.shared.configuration = configuration

    ProgressHUD.success("键盘部署完成！", interaction: false, delay: 1.5)
  }
}
